package com.huawei.cloudapp.model.management;

import static com.huawei.cloudapp.utils.CasCommonUtils.getManagementUrl;
import static com.huawei.cloudapp.utils.CasConstantsUtil.ERROR_CODE;
import static com.huawei.cloudapp.utils.CasConstantsUtil.ERROR_MSG;
import static com.huawei.cloudapp.utils.CasConstantsUtil.LOGIN;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PASSWORD;
import static com.huawei.cloudapp.utils.CasConstantsUtil.SESSION_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.TOKEN;
import static com.huawei.cloudapp.utils.CasConstantsUtil.USER;
import static com.huawei.cloudapp.utils.CasConstantsUtil.USERNAME;

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.huawei.cloudapp.model.OnRequestListener;
import com.huawei.cloudapp.model.IUserModel;
import com.huawei.cloudapp.model.bean.User;
import com.huawei.cloudapp.model.bean.CustomException;
import com.huawei.cloudapp.utils.CasCommonUtils;
import com.huawei.cloudapp.utils.CasHttpUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class UserModel implements IUserModel {

    public static final String TAG = "UserModel";
    private User mUser;
    private String mRegion;

    @Override
    public void getUser(User user, String password, String region, final OnRequestListener<User> onRequestListener) {
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put(USERNAME, user.getIamUsername());
        userInfo.put(PASSWORD, password);
        Gson gson = new Gson();
        String userInfoJson = gson.toJson(userInfo);
        CasHttpUtils.post(getRequestUrl(), null, userInfoJson, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                onRequestListener.onFailure(e);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    onRequestListener.onSuccess(parseResponseToUser(response), 1);
                } catch (Exception e) {
                    onRequestListener.onFailure(e);
                }
            }
        });
        mUser = user;
        mRegion = region;
    }

    @Override
    public List<User> parseResponseToUser(Response response) throws Exception {
        if (response == null) {
            Log.e(TAG, "Failed to get response from server.");
            throw new CustomException.EmptyResponseFromServerException();
        }

        String rspStr = response.body().string();
        if (rspStr.isEmpty()) {
            Log.e(TAG, "Failed to get response from server.");
            throw new CustomException.EmptyResponseFromServerException();
        }

        //处理结果
        Map<String, Object> responseMap = CasCommonUtils.parseJsonMessage(rspStr);
        if (responseMap.containsKey(ERROR_CODE)) {
            Log.e(TAG, "handleGetPhoneListResponse: error msg is " + responseMap.get(ERROR_MSG));
            if (responseMap.get(ERROR_CODE).equals("CPH.MANAGER.USER.00002")) {
                throw new CustomException.LogInInfoErrorException();
            }
            throw new CustomException.FailedToLogInException();
        } else if (!responseMap.containsKey(TOKEN) || !responseMap.containsKey(SESSION_ID)) {
            Log.e(TAG, "handleGetPhoneListResponse: failed to parse response json str, " + responseMap);
            throw new CustomException.FailedToLogInException();
        }

        mUser.getUserToken().put(mRegion, (String)responseMap.get(TOKEN));
        mUser.setUserSessionId((String) responseMap.get(SESSION_ID));

        return new ArrayList<>(Collections.singletonList(mUser));
    }

    public String getRequestUrl() {
        return getManagementUrl() + "/" + USER + "/" + LOGIN;
    }

}
